<template>
  <div class="avatar-test">
    <h1>头像功能测试</h1>
    
    <div class="test-section">
      <h2>1. 创建测试用户</h2>
      <button @click="createUser" :disabled="creating">
        {{ creating ? '创建中...' : '创建测试用户' }}
      </button>
      <div v-if="currentUserId" class="user-info">
        <p>当前用户ID: {{ currentUserId }}</p>
        <p>用户名: {{ currentUserName }}</p>
      </div>
    </div>

    <div class="test-section">
      <h2>2. 用户头像显示</h2>
      <div class="avatar-display">
        <div class="avatar-group">
          <h3>直接通过工具函数获取头像</h3>
          <div v-if="loading" class="avatar-loading">加载中...</div>
          <img v-else :src="avatarUrl" alt="用户头像" class="avatar-image avatar-large" />
        </div>
        <div class="avatar-group">
          <h3>UserAvatar组件</h3>
          <UserAvatar 
            :userId="currentUserId" 
            size="large"
            @load="handleAvatarLoad"
            @error="handleAvatarError"
          />
        </div>
        <div class="avatar-group">
          <h3>SimpleAvatar组件</h3>
          <SimpleAvatar 
            :userId="currentUserId" 
            size="large"
            @load="handleSimpleAvatarLoad"
            @error="handleSimpleAvatarError"
          />
        </div>
        <div class="avatar-status">
          <p>状态: {{ avatarStatus }}</p>
        </div>
      </div>
    </div>

    <div class="test-section">
      <h2>3. 上传头像</h2>
      <div class="upload-section">
        <input 
          type="file" 
          accept="image/*" 
          @change="handleFileChange"
          ref="fileInput"
        />
        <button @click="uploadAvatar" :disabled="!selectedFile || !currentUserId">
          上传头像
        </button>
        <div v-if="uploadResult" class="upload-result">
          {{ uploadResult }}
        </div>
      </div>
    </div>

    <div class="test-section">
      <h2>4. 不同尺寸的头像</h2>
      <div class="avatar-sizes">
        <div class="avatar-item">
          <UserAvatar :userId="currentUserId" size="small" />
          <span>小尺寸</span>
        </div>
        <div class="avatar-item">
          <UserAvatar :userId="currentUserId" size="medium" />
          <span>中尺寸</span>
        </div>
        <div class="avatar-item">
          <UserAvatar :userId="currentUserId" size="large" />
          <span>大尺寸</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, watch } from 'vue'
import UserAvatar from '../components/UserAvatar.vue'
import SimpleAvatar from '../components/SimpleAvatar.vue'
import { createTestUser, uploadImage } from '../api/image'
import { getUserAvatarByUserId } from '@/utils/avatar'

export default {
  name: 'AvatarTest',
  components: {
    UserAvatar,
    SimpleAvatar
  },
  setup() {
    const currentUserId = ref('')
    const currentUserName = ref('')
    const creating = ref(false)
    const avatarStatus = ref('等待用户ID')
    const selectedFile = ref(null)
    const uploadResult = ref('')
    const fileInput = ref(null)
    const avatarUrl = ref('')
    const loading = ref(true)

    const createUser = async () => {
      creating.value = true
      try {
        const response = await createTestUser()
        currentUserId.value = response.data.userId
        currentUserName.value = response.data.username
        avatarStatus.value = '用户创建成功，加载头像中...'
        uploadResult.value = ''
      } catch (error) {
        console.error('创建用户失败:', error)
        uploadResult.value = `创建用户失败: ${error.message}`
      } finally {
        creating.value = false
      }
    }

    const handleAvatarLoad = (url) => {
      avatarStatus.value = 'UserAvatar加载成功'
      console.log('UserAvatar URL:', url)
    }

    const handleAvatarError = (error) => {
      avatarStatus.value = 'UserAvatar加载失败，使用默认头像'
      console.error('UserAvatar错误:', error)
    }

    const handleSimpleAvatarLoad = (url) => {
      avatarStatus.value = 'SimpleAvatar加载成功'
      console.log('SimpleAvatar URL:', url)
    }

    const handleSimpleAvatarError = (error) => {
      avatarStatus.value = 'SimpleAvatar加载失败，使用默认头像'
      console.error('SimpleAvatar错误:', error)
    }

    const handleFileChange = (event) => {
      selectedFile.value = event.target.files[0]
    }

    const uploadAvatar = async () => {
      if (!selectedFile.value || !currentUserId.value) return

      try {
        uploadResult.value = '上传中...'
        
        const formData = new FormData()
        formData.append('file', selectedFile.value)
        formData.append('userId', currentUserId.value)
        formData.append('description', '用户头像')
        formData.append('tags', 'avatar')

        const response = await uploadImage(formData)
        uploadResult.value = `上传成功！文件名: ${response.data.fileName}`
        avatarStatus.value = '头像已更新，重新加载中...'
        
        // 清空文件选择
        if (fileInput.value) {
          fileInput.value.value = ''
        }
        selectedFile.value = null
        // 重新加载头像
        await loadAvatar()
      } catch (error) {
        uploadResult.value = `上传失败: ${error.message}`
        console.error('上传失败:', error)
      }
    }

    const loadAvatar = async () => {
      loading.value = true
      avatarUrl.value = await getUserAvatarByUserId(currentUserId.value)
      loading.value = false
    }

    watch(() => currentUserId.value, loadAvatar, { immediate: true })

    return {
      currentUserId,
      currentUserName,
      creating,
      avatarStatus,
      selectedFile,
      uploadResult,
      fileInput,
      handleAvatarLoad,
      handleAvatarError,
      handleSimpleAvatarLoad,
      handleSimpleAvatarError,
      handleFileChange,
      uploadAvatar,
      avatarUrl,
      loading
    }
  }
}
</script>

<style scoped>
.avatar-test {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.test-section {
  margin-bottom: 40px;
  padding: 20px;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
}

.test-section h2 {
  margin-top: 0;
  color: #333;
}

.user-info {
  margin-top: 10px;
  padding: 10px;
  background: #f8f9fa;
  border-radius: 4px;
}

.user-info p {
  margin: 5px 0;
  font-family: monospace;
}

.avatar-display {
  display: flex;
  align-items: flex-start;
  gap: 30px;
  flex-wrap: wrap;
}

.avatar-group {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10px;
  padding: 15px;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  background: #f8f9fa;
}

.avatar-group h3 {
  margin: 0;
  font-size: 14px;
  color: #666;
}

.avatar-status {
  font-size: 14px;
  color: #666;
}

.upload-section {
  display: flex;
  flex-direction: column;
  gap: 10px;
  max-width: 300px;
}

.upload-section button {
  padding: 8px 16px;
  background: #007bff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.upload-section button:disabled {
  background: #ccc;
  cursor: not-allowed;
}

.upload-result {
  padding: 10px;
  background: #f8f9fa;
  border-radius: 4px;
  font-size: 14px;
  color: #666;
}

.avatar-sizes {
  display: flex;
  gap: 20px;
  align-items: center;
}

.avatar-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
}

button {
  padding: 10px 20px;
  background: #28a745;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

button:hover:not(:disabled) {
  background: #218838;
}

button:disabled {
  background: #ccc;
  cursor: not-allowed;
}

.avatar-image {
  border-radius: 50%;
  object-fit: cover;
  border: 2px solid #e0e0e0;
  transition: all 0.3s ease;
  width: 64px;
  height: 64px;
}

.avatar-loading {
  font-size: 16px;
  color: #888;
  margin: 10px 0;
}
</style> 